package org.pms.servlet;

import com.google.gson.Gson;
import org.pms.dao.ProductDao;
import org.pms.dao.impl.ProductDaoImpl;
import org.pms.dto.ResultDto;
import org.pms.entity.Product;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * 查看所有的商品
 */
@WebServlet("/api/product_list.do")
public class ListAllProductServlet extends BaseServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // 1.通过DAO获取数据库的数据
        ProductDao productDao = new ProductDaoImpl();
        List<Product> list = productDao.selectAll();

        resp.setContentType("application/json;charset=utf-8");
        PrintWriter out = resp.getWriter();
        // 2. 对数据进行处理（格式） -- 先封装到DTO对象中，后再序列为JSON字符串
        ResultDto resultDto = successJson(list);
        String json = new Gson().toJson(resultDto);

        // 3.响应数据到客户端浏览器中
        out.print(json);

        out.flush();
        out.close();

    }
}
